#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<signal.h>
#include<sys/wait.h>
#include<sys/time.h>
#include<fcntl.h>
#include<unistd.h> 
#include<pthread.h>


void catchsigalrm(int signum);

int main(int argc, char* args[])
{
	//设置阻塞;
	int pid, i;
	sigset_t set;
	sigemptyset(&set);
	sigaddset(&set, SIGALRM);

	sigprocmask(SIG_BLOCK, &set, NULL);
		

	for(i = 0; i < 5; i++){
		pid = fork();
		if(pid < 0){
			perror("fork error");
			exit(1);
		}
		if(pid == 0)
			break;
	}

	if(i == 5){
		printf("this is perent, pid = %d\n", getpid());
		int wstatus, wpid = 1;
	
		while(wpid){
			pid = waitpid(0, &wstatus, WNOHANG);
			if(pid == -1){
				perror("waitpid error");
				exit(1);
			}
			
			int wstatus, wpid;
			pid = waitpid(0, &wstatus, 0);
			if(pid < 0){
				perror("waitpid error");
				exit(1);
			}
			if(WIFEXITED(wstatus)){
				printf("the process %d exit by %d\n", wpid, WEXITSTATUS(wstatus));
			}
		}
	
	}
	else{
		printf("this is child procrss %d\n", getpid());	
		struct sigaction act, oldact;
		
		act.sa_flags = 0;
		act.sa_handler = catchsigalrm;
		sigemptyset(&act.sa_mask);

		sigaction(SIGALRM, &act, &oldact);
		
		sigprocmask(SIG_UNBLOCK, &set, NULL);

		struct itimerval newval;

		newval.it_value.tv_sec = i;
		newval.it_value.tv_usec = 0;

		newval.it_interval.tv_sec = 0;
		newval.it_interval.tv_usec = 0;
		
		
		setitimer(ITIMER_REAL , &newval, NULL);
		//alarm()
	//	while(1);
		sleep(i);
	}
	
}

void catchsigalrm(int signum){
	printf("catch: this is child %d\n",getpid());
//	return;
}
